﻿using System.Collections.Generic;

namespace UnityView
{
    public interface IRadioGroupAction
    {
        void Activate(object sender, bool again);
        void Deactivate(object sender);
        bool On();
    }

    public class RadioGroup
    {
        private readonly List<IRadioGroupAction> _actions = new List<IRadioGroupAction>();

        public void Add(IRadioGroupAction action)
        {
            if (_actions.Contains(action)) return;
            _actions.Add(action);
        }

        public void Remove(IRadioGroupAction action)
        {
            _actions.Remove(action);
        }

        public delegate void OnSwitchComplete(List<IRadioGroupAction> actions);
        public event OnSwitchComplete SwitchComplete;

        protected IRadioGroupAction CurrentAction = null;
        public void On(IRadioGroupAction action)
        {
            if (CurrentAction == action)
            {
                CurrentAction.Activate(action, true);
                return;
            }
            CurrentAction = action;
            IRadioGroupAction selectAction = null;
            foreach (var a in _actions)
            {
                if (action == a)
                {
                    selectAction = a;
                }
                else
                {
                    a.Deactivate(a);
                }
            }
            selectAction?.Activate(selectAction, false);
            SwitchComplete?.Invoke(_actions);
        }

        public void CloseAll()
        {
            foreach (IRadioGroupAction action in _actions)
            {
                action.Deactivate(action);
            }
            SwitchComplete?.Invoke(_actions);
        }
    }
}
